package com.nx.platform.es.bean.modle.rescore;

import com.google.common.base.Preconditions;
import com.google.common.base.Strings;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Lists;
import com.nx.platform.es.bean.modle.score.ScoreFunctionField;
import com.nx.platform.es.common.utils.MoreMaps;
import org.apache.commons.collections4.MapUtils;
import org.elasticsearch.search.rescore.RescorerBuilder;

import java.util.List;
import java.util.Map;

/**
 * @author
 * @since 2016年10月15日
 */
public class RescoreField {

    private final int windowSize;
    private final RescoreFieldType type;
    private final ImmutableMap<String, ?> config;
    private final List<ScoreFunctionField> scoreFunctionFields;

    private RescoreField(RescoreFieldType type, ImmutableMap<String, ?> config,
            List<ScoreFunctionField> scoreFunctionFields) {
        this.windowSize = MapUtils.getIntValue(config, "window_size", 0);
        this.type = type;
        this.config = config;
        this.scoreFunctionFields = scoreFunctionFields;
    }

    public static RescoreField create(Map<?, ?> settings) {
        String type = MoreMaps.getString(settings, "type");
        Preconditions.checkState(!Strings.isNullOrEmpty(type), "type not found");
        RescoreFieldType fieldType = RescoreFieldType.valueOf(type);
        List<ScoreFunctionField> scoreFunctionFields = Lists.newLinkedList();
        ImmutableMap<String, ?> config = fieldType.getParser().parse(settings);
        List<Map<?, ?>> scores = MoreMaps.getObject(settings, "scores");
        if (scores != null) {
            for (Map<?, ?> score : scores) {
                scoreFunctionFields.add(ScoreFunctionField.create(score));
            }
        }
        return new RescoreField(fieldType, config, scoreFunctionFields);
    }

    public RescorerBuilder<?> handle(Map<String, Object> params) {
        return type.getHandler().handle(config, scoreFunctionFields, params);
    }

    public RescoreFieldType getType() {
        return type;
    }

    public int getWindowSize() {
        return windowSize;
    }

    public ImmutableMap<String, ?> getConfig() {
        return config;
    }

    public List<ScoreFunctionField> getScoreFunctionFields() {
        return scoreFunctionFields;
    }

}
